package com.yy.net 
{
	
	import com.yy.net.event.EventCenter;
	import com.yy.net.event.SocketEvent;
	import com.yy.net.socketclass.COMMANDTYPE;
	import com.yy.net.socketclass.MySocket;
	import com.yy.net.socketclass.MySocketEvent;
	
	import flash.events.EventDispatcher;
	
	/**
	 * ...
	 * @author jj043
	 */
	public class ProcessNetCmd
	{
		private var _mysocket:MySocket = null;
		private var m_proces_server:ProcessCmd = null;
		
		
		private var _processFuncs:Object = {};
		public function ProcessNetCmd(m_p:ProcessCmd)
		{
			_mysocket = new MySocket();
			_mysocket.addEventListener(MySocketEvent.CLOSE, onClose);
			_mysocket.addEventListener(MySocketEvent.CONNECT, onConnection);
			_mysocket.addEventListener(MySocketEvent.ERROR, onError);
			_mysocket.addEventListener(MySocketEvent.SYNC, onRecData);	
			
			m_proces_server = m_p;
		}
		
		/**
		 *注册命令处理回调函数 
		 * @param key
		 * @param func
		 * 
		 */
		public function register(key:int, func:Function):void {
			this._processFuncs[key] = func;
		}
		
		public function getMySocket():MySocket
		{
			return _mysocket;
		}
		
		private function onRecData(e:MySocketEvent):void 
		{
			e = null;
			var cmd:int = _mysocket.getcmd();
trace("收到后台命令:0x" + cmd.toString(16));
			var func:Function = this._processFuncs[cmd]
			if(Boolean(func)) {
				func(this._mysocket);
			}else {
				trace("命令号没有对应的处理函数：" + cmd.toString(16));
			}
		}
		
		private function connectSuccess():void
		{
			m_proces_server.connectSuccess();
		}
		
		private function onError(e:MySocketEvent):void 
		{
			trace("连接后台出错");
			EventCenter.SocketEvent.dispatchEvent(new SocketEvent(SocketEvent.CONNECT_FAILURE));
		}
		
		private function onConnection(e:MySocketEvent):void 
		{
			trace("连接成功");
			EventCenter.SocketEvent.dispatchEvent(new SocketEvent(SocketEvent.CONNECT_SUCCESS));
		}
		
		
		private function onClose(e:MySocketEvent):void 
		{
			trace("连接后台关闭");
			EventCenter.SocketEvent.dispatchEvent(new SocketEvent(SocketEvent.CONNECT_FAILURE));
		}
	}
	
}